package com.puppet.task;

import com.common.puppet.BookConst;
import com.common.puppet.RedisConst;
import com.puppet.pojo.BookType;
import com.puppet.service.BookService;
import com.puppet.service.BookTypeService;
import net.bytebuddy.description.type.TypeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class BookMallTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BookService bookService;
    @Autowired
    private BookTypeService bookTypeService;

    @Scheduled(cron="0/30 * 8 * * ?")  //每隔30秒执行一次
    public void execute()  {
        //1、同步热销数据：删除redis中的旧数据，重新查询Mysql数据。写入redis中
        Set<String> keys = redisTemplate.keys(RedisConst.BOOK_LIST + "*");
        keys.forEach(key -> redisTemplate.delete(key));
        //重新查询mysql数据
        bookService.findTopSales(BookConst.FIRST_PAGE,BookConst.PAGE_SIZE);

        //2、同步分类数据,删除redis中的旧数据，
        redisTemplate.delete(redisTemplate.keys(RedisConst.BOOK_TYPE_LIST + "*"));
        // 重新查询mysql数据
        List<BookType> typeList = bookTypeService.findAll();

        //3、查询每个类型下的图书
        typeList.forEach(type -> {
            bookService.findByType(BookConst.FIRST_PAGE,BookConst.PAGE_SIZE,type.getId());
        });
    }
}
